
import os
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

sys.path.append(os.path.dirname(__file__))
import runtest

context = None
def init(context_):
    global context
    context = context_

class ActionNewNode:
    def __init__(self, kind, node):
        self._kind = kind
        self._node = node
    def __del__(self):
        pass
    def on_runtest(self, value):
        global context
        # 执行测试用例
        # 生成测试代码
        # 生成驱动
        # 编译
        # 监控、执行
        # 覆盖率读取
        # 用例执行状态读取
        data_service = context.find_service("DataService")
        project = data_service.root_node()

        procedures = project.get_allchildren_by_kind('Procedure')
        
        usr = self._node.get_prop('usr')

        cur_procedure = None
        for procedure in procedures:
            if procedure.get_prop('usr') == usr:
                cur_procedure = procedure
                break

        if cur_procedure == None:
            print("Error：No procedure is selected!")
            return 

        runtest.gen_testcode(project, self._node, cur_procedure, "")
        runtest.gen_drivercode(project, self._node, cur_procedure, "")
        runtest.build(project, self._node, cur_procedure, "")
        runtest.run(project, self._node, cur_procedure, "")
        runtest.get_coverage(project, self._node, cur_procedure, "")

class DataExploreMenu:
    def __init__(self):
        self.menus = []
    def priorty(self):
        return 1000
    def add_menu(self, menu, nodes):
        self.menus = []
    
        kind = ""
        if len(nodes) == 1:
            kind = node.get_kind()
            if kind != "TestCase":
                return 

            action = menu.addAction("执行测试用例")

            obj = ActionNewNode(kind, node)
            self.menus.append(obj)
            action.triggered.connect(obj.on_runtest)


config = {
    'pluginid': 'UnitTest::UI::RunTest',
    "extensions" : [
        {
            "name": "PL::DataExplore::Menu",
            "id": "PL::DataExplore::Menu::UT::TestCaseRun",
            "impl": DataExploreMenu()
        }
    ]
}